//
//  OAuthViewController.swift
//  SinaWebo
//
//  Created by apple on 16/6/13.
//  Copyright © 2016年 apple. All rights reserved.
/**
App Key：4068182242
App Secret：f6fe75b7e82b8df588cbe78fa69756dc
*/
//

import UIKit
import SVProgressHUD
import AFNetworking

let client_id = "2394854999"
let redirect_uri = "http://www.itcast.cn"
let client_secret = "2abb2a3b03e52a21d2bcb6f5939731ae"
class OAuthViewController: UIViewController {

    let oauthWebView = UIWebView()
    
    override func loadView() {
        view = oauthWebView
       // view.backgroundColor = UIColor.whiteColor()
        oauthWebView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        print(__FUNCTION__)
       view.backgroundColor = UIColor.whiteColor()
        loadOAuthView()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试", style: .Plain, target: self, action: "test")

        // Do any additional setup after loading the view.
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
  @objc  private func test() {
        let jsString = "document.getElementById('userId').value = '13436933947' , document.getElementById('passwd').value = '55555huo' "
        //通过一个字符串对象来执行 javascript代码
        oauthWebView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    func close() {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
 
    //加载授权页面
    private func loadOAuthView() {
        print(__FUNCTION__)
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id="+client_id+"&redirect_uri="+redirect_uri
        let url = NSURL(string: urlString)!
        let request = NSURLRequest(URL: url)
        oauthWebView.loadRequest(request)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
//分类扩展 遵守协议
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
      //获取code码
        print(__FUNCTION__)
        guard let urlstring = request.URL?.absoluteString else { return false }
        print(urlstring)
        //获取url参数
        if urlstring.containsString("code") {
            guard let query = request.URL?.query else { return false }
                let codeKey = "code="
                let codeValue = (query as NSString).substringFromIndex(codeKey.characters.count)
                print(codeValue)
                loadAccessToken(codeValue)
        }
        return true
        
    }
 
    //加载token 2.00AG7EQGcCg_8Ef4a1a2cdaf09yc85
    func loadAccessToken(code: String) {
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
     
        let urlstring = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret": client_secret ,"grant_type":"authorization_code","code":code, "redirect_uri":redirect_uri]

        AFN.POST(urlstring, parameters: parameters, progress: nil, success: { (_, result) -> Void in
        
        print("success",result!)
        guard let dict = result as? [String:AnyObject] else {return }
        print(dict["access_token"]!)
//           let access_token =  dict["access_token"] as! String
//           let uid = dict["uid"] as! String
          //  self.loadUserInfo(access_token, userId: uid)
        }) { (_, error) -> Void in
            print(error)
        }
    }
    
    //获取用户信息
    func loadUserInfo(token: String, userId: String) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":token,"uid":userId]
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result)
            }) { (_, error) -> Void in
                print(error)
        }
        
    }
}
